#include <stdlib.h>
#include <avr/io.h>
#include <string.h>
#include <util/delay.h>

#include "morse.h"


/* unit is in milliseconds */
int unit = 1200 / WPM;
uint8_t i = 0;
uint8_t f = 0;



void sendCode(uint8_t* text, uint8_t* PORT, uint8_t MASK){

/* 
Unit = 1200 / WPM

Dash length = unit x 3
Pause between elements = unit 
Pause between characters= unit x 3
Pause between words = unit x 7

ASCII 0-9, 48 - 57
ASCII A-Z, 66 - 91
*/

	for(i =0; i < strlen(text); i++)
	{
		uint8_t evalMe = 0;
		
		/* character is a space */
		if( text[i] == ' ' ){
			
			_delay_us(unit*7);
		}
	
		/* character is a number */
		else if( text[i] < 58 ){

			/* subtract by 48, and map to morse array */
			evalMe = morse[text[i] - 57];
	
			doChar(evalMe, PORT, MASK);
	
		/* character is a letter */
		} else {
			/* subtract 56, leave 10 offset as they are numbers */
			evalMe = morse[text[i] - 56];
		
			doChar(evalMe, PORT, MASK);
		
		}
	
		/* pause for 3 dots for next character */
		_delay_us(unit*3);
	
	}


}

void doChar(uint8_t evalMe, uint8_t* PORT, uint8_t MASK ){

	uint8_t startEval = 0;
	uint8_t buffer = 0;
	
	/* shift until we find the first bit marking the start of the sequence */
	for( f = 0; f < 8; f++ ){
	
		/* check from the MSbit */
		buffer = (evalMe  >> (7 - f)) & 0x01;
			
		if( startEval ){
		
				/* dash */
				if(buffer){
			
					(*PORT) |= MASK;
					
					_delay_us(unit*3);
					
					(*PORT) &= ~MASK;
								
				}
			
				/* dot */
				else{
			
					(*PORT) |= MASK;
				
					_delay_us(unit);
				
					(*PORT) &= ~MASK;
								
				}
					
				
			/* next element */
			_delay_us(unit);
			
		}else if(buffer){
		
			startEval = 1;
		}
	
	}
}